package com.wpf.system.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wpf.system.entity.*;
import com.wpf.system.entity.dto.BookRentBuySearchDTO;
import com.wpf.system.entity.dto.OrdersSearchDTO;
import com.wpf.system.entity.vo.OrdersVO;
import com.wpf.system.entity.vo.PageVO;
import com.wpf.system.service.*;
import com.wpf.system.mapper.OrdersMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
* @author ferna
* @description 针对表【orders(订单表)】的数据库操作Service实现
* @createDate 2023-02-04 19:22:33
*/
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService{

    @Resource
    private FieldBookService fieldBookService;

    @Resource
    private EquipmentService equipmentService;

    @Resource
    private EquipmentRentService equipmentRentService;

    @Resource
    private EquipmentBuyService equipmentBuyService;

    @Resource
    private PointJournalService pointJournalService;

    @Resource
    BalanceJournalService balanceJournalService;

    @Override
    public PageVO<OrdersVO> getUserOrders(OrdersSearchDTO ordersSearchDTO) {
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Orders::getCreateTime);
        if(ObjectUtil.isNotNull(ordersSearchDTO.getUid())){
            queryWrapper.eq(Orders::getUid,ordersSearchDTO.getUid());
        }
        if(StrUtil.isNotBlank(ordersSearchDTO.getType())){
            List<Long> typeList = Convert.toList(Long.class,ordersSearchDTO.getType().split(","));
            queryWrapper.in(Orders::getType,typeList);
        }
        if(StrUtil.isNotBlank(ordersSearchDTO.getNo())){
            queryWrapper.like(Orders::getNo,ordersSearchDTO.getNo());
        }
        if(StrUtil.isNotBlank(ordersSearchDTO.getStartTime())&&StrUtil.isNotBlank(ordersSearchDTO.getEndTime())){
            queryWrapper.between(Orders::getCreateTime,ordersSearchDTO.getStartTime(),ordersSearchDTO.getEndTime());
        }
        IPage<Orders> ordersIPage = this.baseMapper.selectPage(new Page<>(ordersSearchDTO.getPage(),ordersSearchDTO.getPageSize()),queryWrapper);
        PageVO<OrdersVO> ordersPageVO = new PageVO<>();
        ordersPageVO.setTotal(Convert.toInt(ordersIPage.getTotal()));
        List<OrdersVO> ordersVOList = new ArrayList<>();
        for(Orders o : ordersIPage.getRecords()){
            OrdersVO ordersVO = new OrdersVO();
            ordersVO.setOrders(o);
            BookRentBuySearchDTO noDTO = new BookRentBuySearchDTO();
            noDTO.setNo(o.getNo());
            switch (o.getType()){
                case 0:
                    ordersVO.setFieldBookList(fieldBookService.getAllFieldBook(noDTO));
                    break;
                case 1:
                    ordersVO.setEquipmentRentList(equipmentRentService.getAllEquipmentRent(noDTO));
                    break;
                case 2:
                    ordersVO.setEquipmentBuyList(equipmentBuyService.getAllEquipmentBuy(noDTO));
                    break;
                default:
                    break;
            }
            ordersVOList.add(ordersVO);
        }
        ordersPageVO.setList(ordersVOList);
        return ordersPageVO;
    }

    @Override
    public Orders addNewOrders(Orders orders,List<Long> ids) {
        if(Convert.toBool(this.baseMapper.insert(orders))){
            if(orders.getType()==0){
                //订单关联预约记录
                List<FieldBook> updateFieldBookList = new ArrayList<>();
                ids.forEach(item->{
                    FieldBook updateFieldBook = fieldBookService.getById(item);
                    updateFieldBook.setOid(orders.getId());
                    updateFieldBookList.add(updateFieldBook);
                });
                if(fieldBookService.updateBatchById(updateFieldBookList)){
                    return orders;
                }
                return null;
            }else if(orders.getType()==1){
                //订单关联租赁记录
                List<EquipmentRent> updateEquipmentRentList = new ArrayList<>();
                ids.forEach(item->{
                    EquipmentRent updateEquipmentRent = equipmentRentService.getById(item);
                    updateEquipmentRent.setOid(orders.getId());
                    updateEquipmentRentList.add(updateEquipmentRent);
                });
                if(equipmentRentService.updateBatchById(updateEquipmentRentList)){
                    return orders;
                }
                return null;
            }else if(orders.getType()==2){
                //订单关联购买记录
                List<EquipmentBuy> updateEquipmentBuyList = new ArrayList<>();
                ids.forEach(item->{
                    EquipmentBuy updateEquipmentBuy = equipmentBuyService.getById(item);
                    updateEquipmentBuy.setOid(orders.getId());
                    updateEquipmentBuyList.add(updateEquipmentBuy);
                });
                if(equipmentBuyService.updateBatchById(updateEquipmentBuyList)){
                    return orders;
                }
                return null;
            }else if(orders.getType()==4){
                balanceJournalService.balanceInto(orders,3,null);
            }
            return orders;
        }
        return null;
    }

    @Override
    public Boolean payOrdersSuccess(Orders orders) {
        if(ObjectUtil.isNotNull(orders.getPoint()) && orders.getPoint()>0){
            //使用积分并记录操作
            pointJournalService.pointOut(orders);
        }
        if(ObjectUtil.isNotNull(orders.getCost()) && orders.getCost().compareTo(BigDecimal.valueOf(0))==1){
            //扣金额记录操作
            balanceJournalService.balanceOut(orders);
            //添加积分并记录操作
            pointJournalService.pointInto(orders,3);
        }

        //改子项目状态
        if(orders.getType()==0){
            List<FieldBook> fieldBookList = fieldBookService.list(new LambdaQueryWrapper<FieldBook>().eq(FieldBook::getOid,orders.getId()));
            for(FieldBook item :fieldBookList){
                item.setStatus(1);
                item.setCode(RandomUtil.randomInt(1000,9999));
            }
            fieldBookService.updateBatchById(fieldBookList);
        }else if(orders.getType()==1){
            List<EquipmentRent> equipmentRentList = equipmentRentService.list(new LambdaQueryWrapper<EquipmentRent>().eq(EquipmentRent::getOid,orders.getId()));
            for(EquipmentRent item :equipmentRentList){
                item.setStatus(1);
                item.setCode(RandomUtil.randomInt(1000,9999));
            }
            equipmentRentService.updateBatchById(equipmentRentList);
        }else if(orders.getType()==2){
            List<EquipmentBuy> equipmentBuyList = equipmentBuyService.list(new LambdaQueryWrapper<EquipmentBuy>().eq(EquipmentBuy::getOid,orders.getId()));
            for(EquipmentBuy item : equipmentBuyList){
                item.setStatus(1);
                item.setCode(RandomUtil.randomInt(1000,9999));
            }
            equipmentBuyService.updateBatchById(equipmentBuyList);
        }

        //改订单状态
        orders.setStatus(1);
        return Convert.toBool(this.baseMapper.updateById(orders));
    }

    @Override
    public void checkOrdersPay(String no) {
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Orders::getNo,no);
        queryWrapper.eq(Orders::getStatus,0);
        Orders orders = this.baseMapper.selectOne(queryWrapper);
        if(ObjectUtil.isNotNull(orders)){
            //订单标记为交易关闭
            orders.setStatus(2);
            this.baseMapper.updateById(orders);
            if(orders.getType()==0){
                //关联预约关闭
                List<FieldBook> fieldBookList = fieldBookService.getBaseMapper().selectList(
                        new LambdaQueryWrapper<FieldBook>().eq(FieldBook::getOid,orders.getId()).eq(FieldBook::getStatus,0) );
                fieldBookList.forEach(item->{
                    //退还积分
                    if(orders.getPoint()>0L){
                        pointJournalService.pointInto(orders,0);
                    }
                    item.setStatus(5);
                });
                fieldBookService.updateBatchById(fieldBookList);
            }else if(orders.getType()==1){
                //关联租赁关闭
                List<EquipmentRent> equipmentRentList = equipmentRentService.getBaseMapper().selectList(
                        new LambdaQueryWrapper<EquipmentRent>().eq(EquipmentRent::getOid,orders.getId()).eq(EquipmentRent::getStatus,0) );
                equipmentRentList.forEach(item->{
                    //退还积分
                    if(orders.getPoint()>0L){
                        pointJournalService.pointInto(orders,1);
                    }
                    //退还库存
                    Equipment equipment = equipmentService.getById(item.getEid());
                    equipment.setNumber(equipment.getNumber()+item.getNumber());
                    equipmentService.updateById(equipment);
                    item.setStatus(5);
                });
                equipmentRentService.updateBatchById(equipmentRentList);
            }else if(orders.getType()==2){
                //关联购买关闭
                List<EquipmentBuy> equipmentBuytList = equipmentBuyService.getBaseMapper().selectList(
                        new LambdaQueryWrapper<EquipmentBuy>().eq(EquipmentBuy::getOid,orders.getId()).eq(EquipmentBuy::getStatus,0) );
                equipmentBuytList.forEach(item->{
                    //退还积分
                    if(orders.getPoint()>0L){
                        pointJournalService.pointInto(orders,2);
                    }
                    //退还库存
                    Equipment equipment = equipmentService.getById(item.getEid());
                    equipment.setNumber(equipment.getNumber()+item.getNumber());
                    equipmentService.updateById(equipment);
                    item.setStatus(4);
                });
                equipmentBuyService.updateBatchById(equipmentBuytList);
            }
        }
    }

}




